package com.gz.mylife.app;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.gz.mylife.R;
import com.gz.mylife.util.ImageUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.util.CrashHandler;

/**
 * 
 * @author 陈希然
 *
 */
public class HDImagePreview extends Activity implements OnPageChangeListener {

	private final static String TAG = "HDImagePreview";
	private TextView mPageText;
	private ViewPager mPager;
	private List<View> mFreeViews;  // 方便回收
	
	private String[] mImageUrls;
	private int mPosition;
	private DisplayImageOptions mOption;
	
	private int sWidth;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_hd_image_preview);
		
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		sWidth = metrics.widthPixels;
		
		mImageUrls = getIntent().getStringArrayExtra("images");
		mPosition = getIntent().getIntExtra("position", 0);
		mOption = buildImageOptions();
		
		mFreeViews = new ArrayList<View>(mImageUrls.length);
		mPageText = (TextView) findViewById(R.id.txt_page);
		mPager = (ViewPager) findViewById(R.id.pager);
		mPager.setAdapter(new ViewPagerAdapter());
		mPager.setCurrentItem(mPosition);
		mPager.setOnPageChangeListener(this);  
		mPageText.setText((mPosition + 1) + "/" + mImageUrls.length);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ImageUtils.unbindDrawables(mPager);
	}
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		CrashHandler.d(TAG, "图片预览对象回收了");
	}
	
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}
	
	private DisplayImageOptions buildImageOptions(){
		return new DisplayImageOptions.Builder()
        .resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheOnDisk(true)
        .cacheInMemory(true)
        .imageScaleType(ImageScaleType.IN_SAMPLE_INT) 
        .showImageOnLoading(R.color.transparent)
        .showImageForEmptyUri(R.color.transparent)
        .showImageOnFail(R.color.transparent)
        .build();
	}
	
	private class ViewPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return mImageUrls.length;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = null;
			if(mFreeViews.size() > 0){
				view = mFreeViews.remove(mFreeViews.size()-1);
			} else {
				view = LayoutInflater.from(HDImagePreview.this).inflate(R.layout.photo_preview_item, null);
			}
			final ImageView imageView = (ImageView) view.findViewById(R.id.iv_photo);
			TextView rateText = (TextView) view.findViewById(R.id.txt_rate);
			
			if(!ImageUtils.isBigPicture(mImageUrls[position])){
				//ImageLoader.getInstance().displayImage(mImageUrls[position], imageView);
				mImageUrls[position] = ImageUtils.getBigPictureUrl(mImageUrls[position]);
			}
			ImageLoader.getInstance().displayImage(mImageUrls[position],imageView, mOption, new MyImageLoadingListener(rateText) {

						@Override
						public void onLoadingStarted(String imageUri, View view) {
							getTextView().setVisibility(View.VISIBLE);
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							getTextView().setVisibility(View.GONE);
							
						}
					}, new MyImageLoadingProgressListener(rateText) {

						int currRate = 0;
						int tempRate = 0;
						
						@Override
						public void onProgressUpdate(String imageUri, View view, int current,
								int total) {
							// TODO Auto-generated method stub
							tempRate = current * 100 / total;
							if (total == current) {
								currRate = 100;
								getTextView().setText(currRate + "%");
								return;
							}
							if (tempRate > currRate) {
								currRate = tempRate;
								getTextView().setText(currRate + "%");
							}
						}
					});
			container.addView(view);
			return view;
		}
		
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			View view = (View) object;  
            container.removeView(view);
            ImageUtils.unbindDrawables(view);
            mFreeViews.add(view);
		}
	}

	
	@Override
	public void onPageScrollStateChanged(int position) {
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int currentPage) {
		mPageText.setText((currentPage + 1) + "/" + mImageUrls.length);
	}
	
}
